from selenium.webdriver.common.by import By

# 显示等待，更加智能
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import json

# 验证码识别
import ddddocr


def save_cookies(driver):
    cookies = driver.get_cookies()
    with open("cookies.json", "w") as f:
        f.write(json.dumps(cookies))


def load_cookies(driver):
    driver.get("http://106.38.235.201:7080/portal/")
    try:
        with open("cookies.json") as f:
            cookies = json.loads(f.read())
        for cookie in cookies:
            driver.add_cookie(cookie)
        driver.refresh()
    except:
        pass


def is_login(driver):
    if "登录" in driver.title:
        print("需要正常登录")
        return False
    else:
        print("已经登录，无需再次登录")
        return True


# 判断是否已经登录
# if is_login(driver) is False:
# 浏览器关闭之前保存cookies
# save_cookies(driver)


# 查找元素并点击
def find_element_click(driver, SearchType, content):
    try:
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((SearchType, content))
        )
        element.click()
        return True
    except Exception as e:
        print("等了10秒没有找到相应元素链接，无法点击，错误：", e)


# 查找元素并输入
def find_element_input(driver, SearchType, content, inputContent):
    try:
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((SearchType, content))
        )
        element.send_keys(inputContent)
        return True
    except Exception as e:
        print("等了10秒没有找到相应元素链接，无法输入，错误：", e)


# 清空输入框内容
def find_element_clear(driver, SearchType, content):
    try:
        element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((SearchType, content))
        )
        element.clear()
        return True
    except Exception as e:
        print("等了10秒没有找到相应元素链接，无法输入，错误：", e)


# 判断元素是否存在页面中
def iselement(driver, SearchType, content):
    try:
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((SearchType, content))
        )
        return True
    except Exception as e:
        print("没有跳转到无任何权限的页面或是元素没有找到", e)
        return False


# 获取验证码并识别
def captcha_processing():
    ocr = ddddocr.DdddOcr()
    with open("jcaptcha.jpg", "rb") as f:
        img_bytes = f.read()
        res = ocr.classification(img_bytes)
    print("验证码为：", res)
    return res


# 国扶系统中-切换选项卡
# driver.switch_to.frame(id)
# 它在iframe中，所以你需要在交互之前切换到它。可以使用以下css_selector切换到iframe：
def switch_tab(driver, prop, content):
    WebDriverWait(driver, 10).until(
        EC.frame_to_be_available_and_switch_to_it(
            (By.CSS_SELECTOR, f"iframe[{prop}='{content}']")
        )
    )
